﻿using BacklogParser.Parsers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace BacklogParser.WinForms
{
    public class Engine
    {


        public void Run(IEnumerable<string> xmlPaths, string folderPath)
        {
            string resultPath = folderPath + "\\Results";
            if (Directory.Exists(resultPath))
            {
                this.EmptyFolder(new DirectoryInfo(resultPath));
            }
            else
                Directory.CreateDirectory(resultPath);

            foreach (var xmlPath in xmlPaths)
            {
                var fileNameIndex = xmlPath.LastIndexOf('\\') + 1;
                string fileName = xmlPath.Substring(fileNameIndex);

                string sqlPath = resultPath + "\\" + fileName.Substring(0, fileName.Length - 4) + ".sql";

                XDocument xdoc = XDocument.Load(xmlPath);

                var documents = xdoc.Descendants(Constants.Epo + "register-document").ToList();
                var result = new List<RegisterDocument>();
                foreach (var item in documents)
                {
                    var parsed = DocumentParser.ParseDocument(item);

                    var sqlGenerator = new SqlGenerator();
                    var builder = sqlGenerator.GenerateSqlForDocument(parsed);

                    using (var writer = new StreamWriter(sqlPath, true, Encoding.Unicode))
                    {
                        writer.Write(builder.ToString());
                    }

                }
                MessageBox.Show("Done");
                // Console.WriteLine("Done");
            }
        }

        private void EmptyFolder(DirectoryInfo directoryInfo)
        {
            foreach (FileInfo file in directoryInfo.GetFiles())
            {
                file.Delete();
            }

            foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
            {
                EmptyFolder(subfolder);
            }
        }
    }
}
